package com.tihom.security.rbac.service.impl;

import com.tihom.security.rbac.domain.Admin;
import com.tihom.security.rbac.service.RbacService;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.social.security.SocialUser;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.*;


/**
 * @author TiHom
 */
@Component("rbacService")
public class RbacServiceImpl implements RbacService {

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    public RbacServiceImpl() {
        System.out.println("初始化RbacServiceImpl");
    }

    @Override
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        Object principal = authentication.getPrincipal();
        System.out.println("校验rbacService...");
        boolean hasPermission = false;

        if (principal instanceof Admin) {
            //如果用户名是admin，就永远返回true
            if (StringUtils.equals(((Admin) principal).getUsername(), "admin")) {
                hasPermission = true;
            } else {
                // 读取用户所拥有权限的所有URL
                Set<String> urls = ((Admin) principal).getUrls();
                for (String url : urls) {
                    if (antPathMatcher.match(url, request.getRequestURI())) {
                        hasPermission = true;
                        break;
                    }
                }
            }
        }
        if (principal instanceof SocialUser) {
            SocialUser socialUser = (SocialUser) principal;
            //如果用户名是admin，就永远返回true
            if (StringUtils.equals(socialUser.getUsername(), "admin")) {
                hasPermission = true;
            } else {
                // 读取用户所拥有权限的所有URL
                Collection<GrantedAuthority> authorities = socialUser.getAuthorities();

                for (GrantedAuthority grantedAuthority : authorities) {
                    String roles = grantedAuthority.getAuthority();
                    if (!roles.startsWith("ROLE_")) {
                        continue;
                    }
                    //TODO 获取角色
                    String role = roles.substring(5).toUpperCase();
                    List<String> urls = getRoleUrls(role);
                    for (String url : urls) {
                        if (antPathMatcher.match(url, request.getRequestURI())) {
                            hasPermission = true;
                            break;
                        }
                    }
                }
            }
        }

        return hasPermission;
    }

    private List<String> getRoleUrls(String role) {
        if ("admin2".toUpperCase().equals(role)) {
            return Arrays.asList("/new/**", "/test/**");
        }
        return new ArrayList<>();
    }

}
